package cn.easybuy.servlet.pre;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.easybuy.entity.Product;
import cn.easybuy.service.ProductService;
import cn.easybuy.service.impl.ProductServiceImpl;
import cn.easybuy.util.PageUtil;
public class ProductServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	
	private ProductService productService = new ProductServiceImpl();
       
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
		response.setContentType("text/html;charset=utf-8");
		String action = request.getParameter("action");
		if (action != null && action.length()>0) {
			switch (action) {
			case "queryList":
				queryList(request,response);
				break;
			case "queryDeatil":
				queryDeatil(request,response);
				break;
			default:
				response.sendRedirect("404.jsp");
				break;
			}
		} else {
			response.sendRedirect("404.jsp");
		}
		
	}
	
	public void queryDeatil(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
        String id = request.getParameter("id");
        Product product = productService.getProductById(Integer.valueOf(id));
        request.setAttribute("product", product);
        request.getRequestDispatcher("pre/productDeatil.jsp").forward(request, response);
    }
	
	private void queryList(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String categoryId = request.getParameter("categoryId");
		String categoryLevel = request.getParameter("categoryLevel");
		
		int currPageNo = Integer.parseInt(request.getParameter("currPageNo"));
		int pageSize = 4;
		
		
		PageUtil<Product> pageUtil = productService.findProductsByCategoryId(Integer.parseInt(categoryId),Integer.parseInt(categoryLevel),currPageNo,pageSize);
		
		pageUtil.setCurrPageNo(currPageNo);
		//listProduct
		request.setAttribute("pageUtil", pageUtil);
		
		request.getRequestDispatcher("pre/queryProductList.jsp").forward(request, response);
		
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
